package com;

import com.swftools.SwfToolsUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class FileUtil {
    private final static Logger log = Logger.getLogger(FileUtil.class);

    // 文件下载
    public static void dowloadFile(String fileName, String path,
                                   HttpServletResponse response) {
        InputStream inStream = null;
        try {
            inStream = new FileInputStream(path);
            // String name = fileName+path.substring(path.lastIndexOf("."));
            fileName = new String(fileName.getBytes("GBK"), "ISO8859-1");
            // 设置输出格式
            response.reset();
            response.setContentType("bin");
            response.addHeader("Content-Disposition", "attachment;filename="
                    + fileName);
            // 循环输出流数据
            byte[] b = new byte[100];
            int len;
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);

            // 关闭流
            inStream.close();
            response.getOutputStream().close();
            log.info("==============dowloadFile下载成功===============");
        } catch (Exception e) {
            log.info("==============dowloadFile下载失败===============", e);
            e.printStackTrace();
        }
    }

    // 文件上传（返回文件的大小M）
    public static String getUpload(String path, String filenameNew,
                                   File temppath) {
        String msize = "";
        try {
            File file = new File(path);
            if (!file.exists())
                file.mkdirs();// 创建文件目录

            file = new File(path, filenameNew);
            if (!file.exists())
                file.createNewFile();// 创建文件

            // 往相应目录写文件
            InputStream is = new FileInputStream(temppath);
            OutputStream os = new FileOutputStream(file);
            int size = is.available();// 文件字节数
            int sizeM = size / 1024;
            msize = String.valueOf(sizeM);
            byte[] bytefer = new byte[size];
            int length = 0;
            while ((length = is.read(bytefer)) != -1) {
                os.write(bytefer, 0, length);
            }
            os.close();
            is.close();

            // 生成pdf和swf文件
            SwfToolsUtil.convert2SWF(path + "/" + filenameNew);
            log.info("==============getUpload上传成功===============");
        } catch (Exception e) {
            log.info("==============getUpload上传失败===============", e);
            e.printStackTrace();
        }
        return msize;
    }

    // 删除文件
    public static void getDelete(String path) {
        File file = new File(path);
        if (file.exists())
            file.delete();// 删除原文件
        String pdfFile = getFilePrefix2(path) + ".pdf";
        File file2 = new File(pdfFile);
        if (file2.exists())
            file2.delete();// 删除pdf文件
        String swfFile = getFilePrefix2(path) + ".swf";
        File file3 = new File(swfFile);
        if (file3.exists())
            file3.delete();// 删除swf文件
        log.info("==============getDelete删除附件成功===============");
    }
    /**
     * 获取文件扩展名
     *
     * @param filename
     * @return
     */
    public static String getExtend(String filename) {
        return getExtend(filename, "");
    }

    /**
     * 获取文件扩展名
     *
     * @param filename
     * @return
     */
    public static String getExtend(String filename, String defExt) {
        if ((filename != null) && (filename.length() > 0)) {
            int i = filename.lastIndexOf('.');

            if ((i > 0) && (i < (filename.length() - 1))) {
                return (filename.substring(i+1)).toLowerCase();
            }
        }
        return defExt.toLowerCase();
    }

    /**
     * 获取文件名称[不含后缀名]
     *
     * @param
     * @return String
     */
    public static String getFilePrefix(String fileName) {
        int splitIndex = fileName.lastIndexOf(".");
        return fileName.substring(0, splitIndex).replaceAll("\\s*", "");
    }

    /**
     * 获取文件名称[不含后缀名]
     * 不去掉文件目录的空格
     * @param
     * @return String
     */
    public static String getFilePrefix2(String fileName) {
        int splitIndex = fileName.lastIndexOf(".");
        return fileName.substring(0, splitIndex);
    }

    /**
     * 文件复制
     *方法摘要：这里一句话描述方法的用途
     *@param
     *@return void
     */
    public static void copyFile(String inputFile,String outputFile) throws FileNotFoundException{
        File sFile = new File(inputFile);
        File tFile = new File(outputFile);
        FileInputStream fis = new FileInputStream(sFile);
        FileOutputStream fos = new FileOutputStream(tFile);
        int temp = 0;
        byte[] buf = new byte[10240];
        try {
            while((temp = fis.read(buf))!=-1){
                fos.write(buf, 0, temp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                fis.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 判断文件是否为图片<br>
     * <br>
     *
     * @param filename
     *            文件名<br>
     *            判断具体文件类型<br>
     * @return 检查后的结果<br>
     * @throws Exception
     */
    public static boolean isPicture(String filename) {
        // 文件名称为空的场合
        if (StringUtils.isEmpty(filename)) {
            // 返回不和合法
            return false;
        }
        // 获得文件后缀名
        //String tmpName = getExtend(filename);
        String tmpName = filename;
        // 声明图片后缀名数组
        String imgeArray[][] = { { "bmp", "0" }, { "dib", "1" },
                { "gif", "2" }, { "jfif", "3" }, { "jpe", "4" },
                { "jpeg", "5" }, { "jpg", "6" }, { "png", "7" },
                { "tif", "8" }, { "tiff", "9" }, { "ico", "10" } };
        // 遍历名称数组
        for (int i = 0; i < imgeArray.length; i++) {
            // 判断单个类型文件的场合
            if (imgeArray[i][0].equals(tmpName.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断文件是否为DWG<br>
     * <br>
     *
     * @param filename
     *            文件名<br>
     *            判断具体文件类型<br>
     * @return 检查后的结果<br>
     * @throws Exception
     */
    public static boolean isDwg(String filename) {
        // 文件名称为空的场合
        if (StringUtils.isEmpty(filename)) {
            // 返回不和合法
            return false;
        }
        // 获得文件后缀名
        String tmpName = getExtend(filename);
        // 声明图片后缀名数组
        if (tmpName.equals("dwg")) {
            return true;
        }
        return false;
    }

    /**
     * 删除指定的文件
     *
     * @param strFileName
     *            指定绝对路径的文件名
     * @return 如果删除成功true否则false
     */
    public static boolean delete(String strFileName) {
        File fileDelete = new File(strFileName);

        if (!fileDelete.exists() || !fileDelete.isFile()) {
            //LogUtil.info("错误: " + strFileName + "不存在!");
            return false;
        }

        //LogUtil.info("--------成功删除文件---------"+strFileName);
        return fileDelete.delete();
    }

    /**
     *
     * @Title: encodingFileName 2015-11-26 huangzq add
     * @Description: 防止文件名中文乱码含有空格时%20
     * @param @param fileName
     * @param @return    设定文件
     * @return String    返回类型
     * @throws
     */
    public static String encodingFileName(String fileName) {
        String returnFileName = "";
        try {
            returnFileName = URLEncoder.encode(fileName, "UTF-8");
            returnFileName = StringUtils.replace(returnFileName, "+", "%20");
            if (returnFileName.length() > 150) {
                returnFileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
                returnFileName = StringUtils.replace(returnFileName, " ", "%20");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            //   LogUtil.info("Don't support this encoding ...");
        }
        return returnFileName;
    }
}
